package zerous.mytest;

import android.content.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
import java.util.*;
import android.support.design.widget.*;

public class CharViewFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
	List<String> characters, chunks;
	ListView charViewer;
	ArrayAdapter mAdapter, chunksAdapter;
	AlertDialog resetChunk, myChunks;
	TextView cvTextView;
	int cStart, cEnd;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final View ctx = inflater.inflate(R.layout.fragment_cv, container, false);
		
		characters = new ArrayList<String>();
		chunks = new ArrayList<String>();
		
		charViewer = (ListView)ctx.findViewById(R.id.characterViewer);
		cvTextView = (TextView)ctx.findViewById(R.id.cvTextView);
		charViewer.setOnItemClickListener(this);
		charViewer.setOnItemLongClickListener(this);
		
		cvTextView.setVisibility(View.VISIBLE);
		
		mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, characters);

		charViewer.setAdapter(mAdapter);

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		final View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_cv, null);
		builder.setView(v);
		builder.setTitle("选一块区域");
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface in, int value) {
					EditText ss = (EditText)v.findViewById(R.id.startSign);
					EditText es = (EditText)v.findViewById(R.id.endSign);
					String sStr = ss.getEditableText().toString();
					String eStr = es.getEditableText().toString();

					if ("".equals(sStr) || "".equals(eStr)) {
						Toast.makeText(getActivity(), "不能不填啊...", Toast.LENGTH_SHORT).show();
					} else if (sStr.length() > 2 && ((sStr.charAt(0) != 'c' && sStr.length() == 2) || !checkIsNumber(sStr)) && eStr.length() > 2 && ((eStr.charAt(0) != 'c' && eStr.length() == 2) || !checkIsNumber(eStr))) {
						Toast.makeText(getActivity(), "你都填了些什么...", Toast.LENGTH_SHORT).show();
					} else {
						int startPos;
						int endPos;
						if (sStr.length() == 1 && eStr.length() == 1 && !checkIsNumber(sStr) && !checkIsNumber(eStr)) {
							char startChar = sStr.charAt(0);
							char endChar = eStr.charAt(0);
							startPos = startChar;
							endPos = endChar;
						} else if (sStr.charAt(0) == 'c' && sStr.length() == 2 && eStr.charAt(0) == 'c' && eStr.length() == 2) {
							startPos = sStr.charAt(1);
							endPos = eStr.charAt(1);
						} else if (sStr.charAt(0) == 'c' && sStr.length() == 2 && eStr.length() != 1) {
							startPos = sStr.charAt(1);
							endPos = startPos + Integer.valueOf(eStr);
						} else if (sStr.length() == 1 && !checkIsNumber(sStr) && eStr.length() != 1) {
							startPos = sStr.charAt(0);
							endPos = startPos + Integer.valueOf(eStr);
						} else {
							startPos = Integer.valueOf(sStr);
							endPos = Integer.valueOf(eStr);
						}

						if (startPos > endPos) {
							Toast.makeText(getActivity(), "开始点比结束点大？", Toast.LENGTH_SHORT).show();
						} else {
							reset(startPos, endPos);
							mAdapter.notifyDataSetChanged();
						}
						
						cvTextView.setVisibility(View.INVISIBLE);
					}
				}
			}
		);

		resetChunk = builder.create();
		return ctx;
	}

	@Override
	public void onResume() {
		// TODO: Implement this method
		super.onResume();
		
		SharedPreferences sh = getActivity().getSharedPreferences("chunks", Context.MODE_PRIVATE);
		Set<String> chunkData = sh.getStringSet("chunkData", null);
		if (chunkData != null) {
			chunks = new ArrayList<String>(chunkData);
		} else {
			chunks = new ArrayList<String>();
		}
		chunksAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, chunks);

		AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
		b.setAdapter(chunksAdapter, null);
		b.setTitle("已保存的区域");
		b.setNeutralButton(android.R.string.cancel, null);

		myChunks = b.create();
		myChunks.getListView().setOnItemClickListener(this);
		myChunks.getListView().setOnItemLongClickListener(this);
		
		
	}

	@Override
	public void onPause() {
		// TODO: Implement this method
		super.onPause();
		SharedPreferences sh = getActivity().getSharedPreferences("chunks", Context.MODE_PRIVATE);
		SharedPreferences.Editor e = sh.edit();
		Set<String> chunkData = new HashSet<String>(chunks);
		e.putStringSet("chunkData", chunkData);
		e.commit();
	}
	
	
	@Override
	public void onItemClick(AdapterView<?> l, View v, int pos, long p4) {
		if (l.getId() == R.id.characterViewer) {
			final String[] data = characters.get(pos).split(":");
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("选择保存的区域");
			builder.setMessage("当前的字符:" + characters.get(pos));
			builder.setNeutralButton(android.R.string.cancel, null);

			builder.setNegativeButton("设置为开始点", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface in, int v) {
						cStart = Integer.valueOf(data[0]);
					}
				}
			);
			builder.setPositiveButton("设置为结束点", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface in, int v) {
						cEnd = Integer.valueOf(data[0]);
					}
				}
			);
			builder.show();
		} else {
			String[] info = ((String)l.getItemAtPosition(pos)).split(":");
			int s = Integer.valueOf(info[1]);
			int e = Integer.valueOf(info[2]);
			reset(s, e);
			mAdapter.notifyDataSetChanged();
			Toast.makeText(getActivity(), "已切换", Toast.LENGTH_SHORT).show();
			cvTextView.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> l, View view, int position, long p4) {
		if (l.getId() == R.id.characterViewer) {
			ClipboardManager mgr = getActivity().getSystemService(ClipboardManager.class);
			mgr.setText(characters.get(position).split(":")[1]);
			Toast.makeText(getActivity(), "已复制", Toast.LENGTH_SHORT).show();
			return true;
		} else {
			chunks.remove(position);
			chunksAdapter.notifyDataSetChanged();
		}
		return true;
	}
	
	

	public void menuSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.setRange:
				resetChunk.show();
				break;

			case R.id.viewChunk:
				myChunks.show();
				Toast.makeText(getActivity(), "点击加载，长按删除", Toast.LENGTH_SHORT).show();
				break;

			case R.id.createChunk:
				if (cStart == -1) {
					Toast.makeText(getActivity(), "未指定开始点", Toast.LENGTH_SHORT).show();
					break;
				}

				if (cEnd == -1) {
					Toast.makeText(getActivity(), "未指定结束点", Toast.LENGTH_SHORT).show();
					break;
				}

				if (cStart > cEnd) {
					Toast.makeText(getActivity(), "开始点比结束点大？", Toast.LENGTH_SHORT).show();
					break;
				}

				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				final EditText text = new EditText(getActivity());
				text.setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
				text.setHint("输入名字");
				builder.setView(text);
				builder.setTitle("创建区域");
				builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface in, int v) {
							String inputed = text.getEditableText().toString();
							chunks.add(inputed + ":" + cStart + ":" + cEnd);
							cStart = -1;
							cEnd = -1;
						}
					}
				);
				builder.show();
				break;
		}
	}

	public void setMenu(Menu menu, MenuInflater inflater) {
		// TODO: Implement getActivity() metho
		menu.clear();
		inflater.inflate(R.menu.char_view_menu, menu);
	}
	
	private boolean checkIsNumber(String str) {
		for(int i= 0;i < str.length();++i) {
			char a = str.charAt(i);
			if(a < '0' || a > '9') {
				return false;
			}
		}
		return true;
	}

	private void reset(int startPos, int endPos) {
		characters.clear();
		for (int i = startPos;i <= endPos;++i) {
			characters.add(i + ":" + (char)i);
		}
	}
}
